package aorise.com.frame.network;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.hjq.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;


import aorise.com.frame.FsApplication;
import aorise.com.frame.bean.SysUserModel;
import aorise.com.frame.ui.login.LoginActivity;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSource;
import retrofit2.Retrofit;

import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by Admin on 2018/10/9.
 */

public interface ApiService {

    // TODO: 2018/10/22 用户登录
    @FormUrlEncoded
    @POST(HttpUrl.LOGIN)
    Observable<Result<SysUserModel>> login(@Field("account") String username, @Field("password") String password);

    @POST(HttpUrl.LOGIN_OUT)
    Observable<Result> login_out();




    //刷新token
    @FormUrlEncoded
    @POST(HttpUrl.REFRESH_TOKEN)
    Observable<Result<String>> refreshToken(@Field("token") String token, @Field("account") String account);


    class Utils {


        public Utils() {

        }

        public static ApiService getApiService(final Context context) {
            String url = BuildConfig.BASE_URL;
            Retrofit.Builder builder = new Retrofit.Builder();
            Interceptor token = new Interceptor() {//请求头
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    Request original = chain.request();
                    Request request = original.newBuilder()
                            .header("token", ((FsApplication) context.getApplicationContext()).getToken())
//                                            .method(original.method(), original.body())
                            .build();
                    return chain.proceed(request);
                }
            };
            Interceptor interceptor = new Interceptor() {//拦截错误码
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = chain.proceed(request);
                    ResponseBody responseBody = response.body();
                    BufferedSource source = null;
                    if (responseBody != null) {
                        source = responseBody.source();
                        source.request(Long.MAX_VALUE);
                        String respString = source.buffer().clone().readString(Charset.defaultCharset());
                        System.out.println("data:" + respString);
                        JSONObject j = null;
                        try {
                            j = new JSONObject(respString);
                            int code = j.optInt("code");
                            String simpleName = "";
                            if (context instanceof Activity) {
                                simpleName = ((Activity) context).getClass().getSimpleName();
                            }
                            switch (code) {
                                case StatusDefine.SERVER_ERROR:
                                    if (!simpleName.equals("LoginActivity")) {//如果当前不是登录页
                                        ToastUtils.show("服务器出错，进入登录页面！");
                                        SharedPreferences sp = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
                                        sp.edit().clear().apply();
                                        Intent intent = new Intent(context, LoginActivity.class);
                                        context.startActivity(intent);
                                    } else {
                                        ToastUtils.show("服务器出错！");
                                    }
                                    break;
                                case StatusDefine.DATA_FORMAT_ERROR:
                                    ToastUtils.show("数据格式错误!");
                                    break;
                                case StatusDefine.SYS_ERROR:
                                    ToastUtils.show("系统错误!");
                                    break;
                                case StatusDefine.NET_ERROR:
                                    ToastUtils.show("网络请求失败!");
                                    break;
                                case StatusDefine.DB_ERROR:
                                    ToastUtils.show("数据库访问失败!");
                                    break;
                                case StatusDefine.U_INEXISTENCE:
                                    ToastUtils.show("用户不存在!");
                                    break;
                                case StatusDefine.U_PWD_FAILED:
                                    ToastUtils.show("用户密码错误!");
                                    break;
                                case StatusDefine.U_UNACTIVE:
                                    ToastUtils.show("用户未激活!");
                                    break;
                                case StatusDefine.U_NO_TOKEN:
                                    ToastUtils.show("用户未授权!");
                                    break;
                                case StatusDefine.U_EXIST_USER:
                                    ToastUtils.show("用户已经存在!");
                                    break;
                                case StatusDefine.U_UNLOAD:
                                    ToastUtils.show("登录超时，进入登录页面！");
                                    Intent intent = new Intent(context, LoginActivity.class);
                                    SharedPreferences sp = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
                                    sp.edit().clear().apply();
                                    context.startActivity(intent);
                                    break;
                                case StatusDefine.U_PWD_TWO_INCONFORMITY:
                                    ToastUtils.show("两次密码不一致!");
                                    break;
                                case StatusDefine.U_PWD_OLD_FAILED:
                                    ToastUtils.show("原密码不正确!");
                                    break;
                                case StatusDefine.U_CANT_LOGINAPP:
                                    ToastUtils.show("无权登录APP!");
                                    break;
                                case StatusDefine.HAVEPERMISSIOND:
                                    ToastUtils.show("有权限!");
                                    break;
                                case StatusDefine.PERMISSIONDENIED:
                                    ToastUtils.show("权限不足!");
                                    break;
                                case StatusDefine.SERVICE_ERROR:
                                    ToastUtils.show("业务逻辑层出现异常!");
                                    break;
                                case StatusDefine.PARAM_TYPE_ERROR:
                                    ToastUtils.show("传入参数类型异常!");
                                    break;
                                case StatusDefine.FILE_FORMAT_ERROR:
                                    ToastUtils.show("文件格式不正确!");
                                    break;
                                default:
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    return response;
                }
            };

            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
//                    System.out.println("Timetask_" + message.);
                }
            });
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            /**
             * 设置请求超时时间 添加拦截器token，interceptor
             */
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(BuildConfig.CONNECT_TIME, TimeUnit.SECONDS)//超时时间
                    .writeTimeout(BuildConfig.CONNECT_TIME, TimeUnit.SECONDS)
                    .readTimeout(BuildConfig.CONNECT_TIME, TimeUnit.SECONDS)
                    .addInterceptor(token)//添加token
                    .addInterceptor(interceptor)
//                    .addInterceptor(logInterceptor)
//                    .addNetworkInterceptor(interceptor)
                    .build();

            //构建Retrofit设置参数
            Retrofit retrofit = builder.baseUrl(url)
                    .client(client)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()))
                    .build();
            return retrofit.create(ApiService.class);
        }

        public static Observable.Transformer schedulersTransformer() {
            return new Observable.Transformer() {
                @Override
                public Object call(Object observable) {
                    return ((Observable) observable).subscribeOn(Schedulers.io())
                            .unsubscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                }
            };
        }
    }

}

